package com.team9.fitness.service;

import com.team9.fitness.entity.PostLike;
import com.team9.fitness.mapper.CommunityPostMapper;
import com.team9.fitness.mapper.PostLikeMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 帖子点赞服务类
 * 
 * 提供帖子点赞相关的业务逻辑：
 * - 点赞管理：点赞、取消点赞
 * - 状态查询：查询用户点赞状态
 * - 统计功能：统计帖子点赞数量
 * - 事务管理：确保数据一致性
 */
@Slf4j
@Service
public class PostLikeService {

    @Autowired
    private PostLikeMapper postLikeMapper;

    @Autowired
    private CommunityPostMapper communityPostMapper;

    /**
     * 点赞帖子
     */
    @Transactional
    public boolean likePost(Long userId, Long postId) {
        try {
            // 检查是否已经点赞
            PostLike existingLike = postLikeMapper.selectByUserIdAndPostId(userId, postId);
            
            if (existingLike != null && existingLike.getIsLiked()) {
                log.warn("用户已经点赞过该帖子: userId={}, postId={}", userId, postId);
                return false;
            }

            // 创建或更新点赞记录
            PostLike postLike = PostLike.builder()
                    .userId(userId)
                    .postId(postId)
                    .isLiked(true)
                    .build();
            postLike.setCreatedAtIfNull();

            int result = postLikeMapper.insertOrUpdate(postLike);
            if (result > 0) {
                // 更新帖子点赞数量
                int likeCount = postLikeMapper.countLikesByPostId(postId);
                communityPostMapper.updateLikeCount(postId, likeCount);
                
                log.info("帖子点赞成功: userId={}, postId={}, likeCount={}", userId, postId, likeCount);
                return true;
            }
            return false;
        } catch (Exception e) {
            log.error("帖子点赞失败: userId={}, postId={}", userId, postId, e);
            return false;
        }
    }

    /**
     * 取消点赞帖子
     */
    @Transactional
    public boolean unlikePost(Long userId, Long postId) {
        try {
            // 检查是否已经点赞
            PostLike existingLike = postLikeMapper.selectByUserIdAndPostId(userId, postId);
            
            if (existingLike == null || !existingLike.getIsLiked()) {
                log.warn("用户未点赞该帖子: userId={}, postId={}", userId, postId);
                return false;
            }

            // 更新点赞状态为false
            int result = postLikeMapper.updateLikeStatus(userId, postId, false);
            if (result > 0) {
                // 更新帖子点赞数量
                int likeCount = postLikeMapper.countLikesByPostId(postId);
                communityPostMapper.updateLikeCount(postId, likeCount);
                
                log.info("帖子取消点赞成功: userId={}, postId={}, likeCount={}", userId, postId, likeCount);
                return true;
            }
            return false;
        } catch (Exception e) {
            log.error("帖子取消点赞失败: userId={}, postId={}", userId, postId, e);
            return false;
        }
    }

    /**
     * 切换帖子点赞状态
     */
    @Transactional
    public boolean togglePostLike(Long userId, Long postId) {
        try {
            PostLike existingLike = postLikeMapper.selectByUserIdAndPostId(userId, postId);
            
            if (existingLike != null && existingLike.getIsLiked()) {
                // 如果已点赞，则取消点赞
                return unlikePost(userId, postId);
            } else {
                // 如果未点赞，则点赞
                return likePost(userId, postId);
            }
        } catch (Exception e) {
            log.error("切换帖子点赞状态失败: userId={}, postId={}", userId, postId, e);
            return false;
        }
    }

    /**
     * 获取用户点赞状态
     */
    public Boolean getUserLikeStatus(Long userId, Long postId) {
        try {
            PostLike postLike = postLikeMapper.selectByUserIdAndPostId(userId, postId);
            return postLike != null ? postLike.getIsLiked() : false;
        } catch (Exception e) {
            log.error("获取用户点赞状态失败: userId={}, postId={}", userId, postId, e);
            return false;
        }
    }

    /**
     * 获取帖子点赞数量
     */
    public int getPostLikeCount(Long postId) {
        try {
            return postLikeMapper.countLikesByPostId(postId);
        } catch (Exception e) {
            log.error("获取帖子点赞数量失败: postId={}", postId, e);
            return 0;
        }
    }

    /**
     * 获取用户点赞的帖子列表
     */
    public List<PostLike> getUserLikedPosts(Long userId) {
        try {
            return postLikeMapper.selectLikedByUserId(userId);
        } catch (Exception e) {
            log.error("获取用户点赞帖子列表失败: userId={}", userId, e);
            return List.of();
        }
    }

    /**
     * 获取帖子点赞用户列表
     */
    public List<PostLike> getPostLikedUsers(Long postId) {
        try {
            return postLikeMapper.selectLikedByPostId(postId);
        } catch (Exception e) {
            log.error("获取帖子点赞用户列表失败: postId={}", postId, e);
            return List.of();
        }
    }
}
